#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import datetime
import os

from Ump.utils import _exec_pipe, make_dir

from Ump.common.config_base import ConfigManager

from Ump.schedule.jobs.base import JobBase
from Ump.schedule.utils import log_info_run


class BackupJob(JobBase):

    def __init__(self):
        super(BackupJob, self).__init__()
        self.back_dir = self.defs.BACKUP_PATH

    @log_info_run()
    def run(self, context):
        make_dir(self.back_dir)
        config = ConfigManager(self.defs.DB_CFG_PATH, section='mysql')
        user =  config.get('user')
        password = config.get('password')
        database = config.get('database')

        _exec_pipe('mysqldump -u%s -p%s %s > %s/ump_$(date).sql' % (user, password, database, self.back_dir))
        file_list = os.listdir(self.back_dir)
        files = [os.path.join(self.back_dir, f) for f in file_list]
        ret = sorted(files, key=os.path.getctime, reverse=True)
        while len(ret) > 48:
            os.remove(ret.pop())

if __name__ == "__main__":
    print os.path.abspath(os.path.split(os.path.realpath(__file__))[0] + "/../../../../../backup")
    job = BackupJob()
    job.run('context')
